package net.yondervision.hrfsp.sdk.esign.core;

import static net.yondervision.hrfsp.sdk.esign.domain.ESignConstant.URL_PARAM_SEPARATOR;
import static net.yondervision.hrfsp.sdk.esign.domain.ESignConstant.URL_SEPARATOR;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import com.google.common.base.Stopwatch;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import net.yondervision.hrfsp.sdk.esign.core.util.DefaultResultJsonResolver;
import net.yondervision.hrfsp.sdk.esign.domain.AbstractESignResponse;
import net.yondervision.hrfsp.sdk.esign.domain.ESignRequest;
import net.yondervision.hrfsp.sdk.esign.domain.ParamQuery;

/**
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/09/26 22:13
 */
@Slf4j
public class AccessTokenESignClient implements ESignClient {


  @Override
  public <T extends AbstractESignResponse> T execute(ESignRequest<T> request) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    String appId = request.getAppId();
    ParamQuery paramQuery = request.getParamQuery();
    Map<String, Object> paramMap = BeanUtil.beanToMap(paramQuery);
    paramMap.put("appId", appId);
    String params = HttpUtil.toParams(paramMap);
    String url =
        request.getServerHost() + URL_SEPARATOR + request.getVersion() + request.getUrl()
            + URL_PARAM_SEPARATOR + params;
    String resultJson = HttpUtil.createGet(url).execute().body();
    log.info("esign return json is : {}", resultJson);
    T result = DefaultResultJsonResolver.resolve(request, resultJson);
    log.info("the method executed successfully, taking [{}] .",
        stopwatch.stop().toString());
    return result;
  }


}
